<template>
  <el-card class="card" v-infinite-scroll="loadMore" :infinite-scroll-disabled="loading || !hasMore"
    infinite-scroll-distance="100">
    <transition-group name="fade-slide" tag="div">
      <div v-for="item in list" :key="item.id" class="container">
        <avator :src="item.author.avatar" shape="square" size="60px"></avator>
        <div class="right">
          <div class="nickname">{{ item.author.nickname }}</div>
          <div class="time">
            {{ formatTimeAgo(item.updatedAt) }}
          </div>
          <div class="content">
            <expand-content :content="item.content"></expand-content>
            <div class="content-imgs">
              <el-image class="img" v-for="(img, index) in item.images" :key="img" fit="cover" :src="img"
                :initial-index="index" :z-index="9999" :preview-src-list="item.images" />
            </div>
            <div class="info">
              <div v-permission @click="like(item)">
                <component class="icon" :is="item.is_like ? WpfLike : SolarHeartOutline"></component>
                <span>{{ item.like_count || '赞' }}</span>
              </div>
              <div @click="previewComment(item)">
                <IconamoonCommentLight class="icon" />
                <span>{{ item.comment_count || '回复' }}</span>
              </div>
            </div>
            <Comment v-if="item.showReply" @submit="submitComment(item, $event)" />
            <CommentList v-if="item.showReply" :comments="item.commentList || []" />
          </div>
        </div>
      </div>
    </transition-group>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="!hasMore" class="no-more">没有更多了</div>
  </el-card>
  <PublishTalk @publish="resfreshData" />
</template>
<script setup>
import { formatTimeAgo } from '@/utils'
import SolarHeartOutline from '~icons/solar/heart-outline';
import WpfLike from '~icons/wpf/like';
import IconamoonCommentLight from '~icons/iconamoon/comment-light';
import { fetchTalkList, fetchCommentList, commentTalk, likeComment, unlikeComment } from '@/service/module/talk';
import PublishTalk from './cpns/PublishTalk.vue';
import CommentList from './cpns/CommentList.vue';
import Comment from './cpns/comment.vue';
import { useUserStore } from '@/stores/user';
const list = ref([])
const pageIndex = ref(1)
const pageSize = 10
const loading = ref(false)
const hasMore = ref(true)
const resfreshData = ()=>{
  pageIndex.value = 1;
  hasMore.value = true
  loadMore()
}
const loadMore = async () => {
  if (loading.value || !hasMore.value) return
  loading.value = true
  const res = await fetchTalkList({ pageIndex: pageIndex.value, pageSize })
  if (res.list && res.list.length > 0) {
    if(pageIndex.value === 1) {
      list.value = []
      // 滚动到顶部
      document.body.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
    list.value = [...list.value, ...res.list]
    pageIndex.value++
    // 判断是否还有更多
    hasMore.value = list.value.length < res.total
  } else {
    hasMore.value = false
  }
  loading.value = false
}
const submitComment = async (item, { content}) => {
  await commentTalk({
    moment_id: item.id,
    content: content,
  })
  previewComment(item)
}

const like = async (item) => {
  console.log(item)
  const res =item.is_like? await unlikeComment({
    moment_id: item.id
  }) : await likeComment({
    moment_id: item.id
  })
  item.is_like = res.is_like
  item.like_count = res.like_count
}
const previewComment = async(item) => {
  item.showReply = item.showReply ? !item.showReply :true
  if (!item.showReply || item.comment_count === 0) return
  const res = await fetchCommentList({id:item.id})
  item.commentList = buildCommentTree(res.list)
  console.log(res)
}
function buildCommentTree(list) {
  const map = {}
  const roots = []
  list.forEach(item => {
    item.children = []
    map[item.id] = item
  })
  list.forEach(item => {
    if (item.reply_id && map[item.reply_id]) {
      map[item.reply_id].children.push(item)
    } else {
      roots.push(item)
    }
  })
  return roots
}
// 首次加载
loadMore()
</script>
<style lang="scss" scoped>
.card {
  padding: 30px 20px;
  margin-top: var(--header-height);
}
.loading,
.no-more {
  text-align: center;
  color: #888;
  padding: 16px 0;
  font-size: 14px;
}
.container {
  display: flex;
  gap: 10px;
  font-size: 14px;

  .right {
    flex: 1;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }

  .nickname {
    font-weight: 700;
  }

  .time {
    margin-top: 10px;
    font-size: 12px;
    color: #888;
  }

  .content {
    margin: 10px 0 30px;

    .content-imgs {
      margin-top: 20px;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 5px;
      width: fit-content;

      .img {
        width: 150px;
        height: 150px;

        &:only-child {
          // 如果只有一个图片，则宽度为300px
          width: 300px;
          height: auto;
        }
      }
    }

    .info {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-top: 10px;
      >div {
        display: flex;
        align-items: center;
        cursor: pointer;
        // gap: 5px;
      }
      span {
        font-size: 12px;
        cursor: pointer;
      }
    }
  }
}
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.5s cubic-bezier(.34, 1.56, .64, 1);
}

.fade-slide-enter-from {
  // opacity: 0;
  transform: translateY(40px) scale(0.98);
}

.fade-slide-enter-to {
  // opacity: 1;
  transform: translateY(0) scale(1);
}

.fade-slide-leave-from {
  // opacity: 1;
  transform: translateY(0) scale(1);
}

.fade-slide-leave-to {
  // opacity: 0;
  transform: translateY(40px) scale(0.98);
}

</style>